package com.flute.icrawler.framework.framework.container;

import org.apache.log4j.Logger;

import com.flute.icrawler.framework.framework.CrawlUrl;
import com.flute.tools.data.DataIterator;
import com.flute.tools.data.berkeleydb.BerkeleyDatabase;

public class BerkeleySimpleUrlQueue {

	private BerkeleyDatabase urlDatabase;
	private Integer size;
	private String name;

	private static Logger logger = Logger
			.getLogger(BerkeleySimpleUrlQueue.class);

	public BerkeleySimpleUrlQueue(String env, String dbName) {
		this.urlDatabase = BerkeleyManager.getBerkeleyDatabase(env, dbName,
				new UrlNormalBinding(), new UrlStringBinding());
		size = Long.valueOf(urlDatabase.size()).intValue();
		name = dbName;
	}

	public boolean add(CrawlUrl url) {
		synchronized (size) {
			if (!contains(url)) {
				this.urlDatabase.push(url);
				flush();
				size++;
				return true;
			} else {
				logger.info(name + ":echo url = " + url);
				return false;
			}
		}
	}

	public void remove(CrawlUrl url) {
		synchronized (size) {
			if (contains(url)) {

				size--;
				this.urlDatabase.remove(url);

			} else {
				logger.info(name + ":echo url = " + url);
				return;
			}
		}
	}

	/**
	 * 取出并删除
	 * 
	 * @return
	 */
	public CrawlUrl remove() {
		CrawlUrl url = null;
		synchronized (size) {
			url = (CrawlUrl) this.urlDatabase.pop();
			if (url != null) {

				size--;

			}

		}
		return url;
	}

	public DataIterator<Object> iterator(Object key) {
		return this.urlDatabase.iterator(key);
	}

	public boolean contains(CrawlUrl url) {
		return this.urlDatabase.contains(url);
	}

	public void clear() {
		synchronized (size) {
			size = 0;
		}
		urlDatabase.clear();
	}

	public void flush() {
		urlDatabase.flush();
	}

	public synchronized int size() {
		return size;
	}
}
